package com.vote.dao.util;

import java.io.BufferedReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class Tools {

	public static String getNow() {
		return getNow("-");
	}

	public static String getLoginUser() {
		String loginUser = (String) ActionContext.getContext().getSession().get("userId");
		return loginUser;
	}

	public static String getNow(String strDeli) {

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy" + strDeli + "MM" + strDeli + "dd HH:mm:ss");
		return formatter.format(new java.util.Date());

	}

	public static String getNowWithoutHour() {

		return getNowWithoutHour("-");

	}

	public static String getNowWithoutHour(String strDeli) {

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy" + strDeli + "MM" + strDeli + "dd");
		return formatter.format(new Date());

	}

	public static String getMaxDay(int year, int month) {
		if (month == 4 || month == 6 || month == 9 || month == 11)
			return "30";
		if (month == 2)
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
				return "29";
			else
				return "28";
		return "31";
	}

	public static String getTodayYear() {
		return Tools.getYear(new Date());
	}

	public static String getYear(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		return formatter.format(date);
	}

	public static String getMonth(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("MM");
		return formatter.format(date);
	}

	public static String getTodayMonth() {
		return Tools.getMonth(new Date());
	}

	public static String getDay(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("dd");
		return formatter.format(date);
	}

	public static String getTodayDay() {
		return Tools.getDay(new Date());
	}

	public static boolean isHoliday() {
		boolean returnvalue = false;
		java.util.GregorianCalendar now = new java.util.GregorianCalendar();
		if ((now.get(GregorianCalendar.DAY_OF_WEEK) == GregorianCalendar.SATURDAY)
				|| (now.get(GregorianCalendar.DAY_OF_WEEK) == GregorianCalendar.SUNDAY)) {
			returnvalue = true;
		}
		return returnvalue;
	}

	public static boolean isBeforeTime(int hours, int minutes, int seconds) {
		boolean returnvalue = false;
		Calendar sysCal = Calendar.getInstance();
		Calendar tempCal = Calendar.getInstance();

		tempCal.set(Calendar.HOUR_OF_DAY, hours);
		tempCal.set(Calendar.MINUTE, minutes);
		tempCal.set(Calendar.SECOND, seconds);

		return sysCal.before(tempCal);

	}

	public static int getTodayWeekNum() {
		GregorianCalendar now = new GregorianCalendar();
		int i = now.get(Calendar.DAY_OF_WEEK);
		return i;
	}

	public static String getTodayTime() {
		SimpleDateFormat simpe = new SimpleDateFormat("HH:mm");
		String time = simpe.format(new java.util.Date());
		return time;
	}

	public static String getJsonString() {
		HttpServletRequest req = ServletActionContext.getRequest();
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader bread = req.getReader();
			while ((line = bread.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			// System.out.println(e.getStackTrace().toString());
		}
		return json.toString();
	}

	public static Date getDate(Date date, int days) {
		Date dateresult = new Date();
		try {
			DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
			//Create our Gregorian Calendar.  
			GregorianCalendar cal = new GregorianCalendar();

			//Set the date and time of our calendar  
			//to the system&s date and time
			cal.setTime(date);
			cal.add(GregorianCalendar.DAY_OF_MONTH, days);
			dateresult = cal.getTime();
		} catch (Exception e) {
			//System.out.println("exception"+e.toString());
		}
		return dateresult;
	}

	public static String getDateWithOutHour(Date date, int days) {
		Date dateresult = new Date();
		try {
			DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
			//Create our Gregorian Calendar.  
			GregorianCalendar cal = new GregorianCalendar();

			//Set the date and time of our calendar  
			//to the system&s date and time
			cal.setTime(date);
			cal.add(GregorianCalendar.DAY_OF_MONTH, days);
			dateresult = cal.getTime();
		} catch (Exception e) {
			//System.out.println("exception"+e.toString());
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		return formatter.format(dateresult);
	}

	public static long getQuot(String startTime, String endTime) {
		long quot = 0;
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date startDate = ft.parse(startTime);
			Date endDate = ft.parse(endTime);

			quot = endDate.getTime() - startDate.getTime();
			quot = quot / 1000 / 60 / 60 / 24;

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return quot;
	}

	public static boolean validate(String inputStr, String patternStr) {
		Pattern pattern = null;
		pattern = Pattern.compile(patternStr);
		Matcher matcher = pattern.matcher(inputStr);

		if (matcher.matches()) {
			return true;
		}
		return false;
	}

	public static String getHttpHeaders() {
		StringBuffer sb = new StringBuffer();

		String headerName = "";

		HttpServletRequest request = ServletActionContext.getRequest();

		Enumeration headers = request.getHeaderNames();

		while (headers.hasMoreElements()) {
			headerName = (String) headers.nextElement();

			sb.append(headerName + ": " + request.getHeader(headerName) + "\r\n");
		}

		sb.append("remote: " + request.getRemoteAddr() + " " + request.getRemotePort());

		return sb.toString();
	}

	public static String getDate(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		return formatter.format(date);
	}

	public static Date getDate(String dateString) {
		Date date = null;

		try {
			date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return date;
	}

	public static Date getSimpleDate(String dateString) {
		Date date = null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return date;
	}
	
	// 获得当前日期与本周一相差的天数
    private static int getMondayPlus(){
    	
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return -6;
        } else {
            return 2 - dayOfWeek;
        }
        
    }
	
	  // 获得上周星期一的日期
    public static String getPreviousMondayDate() {        
        int mondayPlus = getMondayPlus();
        
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * -1);
        Date monday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preMonday = df.format(monday);
        return preMonday;
    }
    
    // 获得上周星期日的日期
    public static String getPreviousSundayDate(){
    	
    	int mondayPlus = getMondayPlus();
        
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus-1);
        Date sunday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preSunday = df.format(sunday);
        
        return preSunday;    	
    }
    
    //获得本周一的日期
    public static String getTheMondayDate(){
    	int mondayPlus = getMondayPlus();
        
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date sunday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preSunday = df.format(sunday);
        
        return preSunday;    	
    }
    
    //获得本周日的日期
    public static String getTheSundayDate(){
    	int mondayPlus = getMondayPlus();
        
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus+6);
        Date sunday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preSunday = df.format(sunday);
        
        return preSunday;    	
    }
	

	public static long getConfirmCode() {
		long ret = 0;

		Random rand = new Random();

		rand.setSeed(System.nanoTime());

		ret = Math.abs(rand.nextLong());

		ret = ret % 999999999999L;

		if (ret < 100000000000L) {
			ret += 100000000000L;
		}

		return ret;
	}

	public static String[] stringToArray(String str, String strDeli) {
		int intNum;
		String[] strArray = null;
		try {
			StringTokenizer strcStr = new StringTokenizer(str, strDeli);
			intNum = strcStr.countTokens();
			strArray = new String[intNum];
			for (int i = 0; i < intNum; i++) {
				strArray[i] = strcStr.nextToken();
			}
			return (strArray);
		} catch (Exception e) {
			return (null);
		}
	}

	public static String arrayToString(String[] strArr, String strDeli) {
		StringBuffer sb = new StringBuffer();
		if (strArr == null || strArr.length < 1) {
			return null;
		}
		try {
			for (int i = 0; i < strArr.length; i++) {
				sb.append(strArr[i]);
				if (i != strArr.length - 1)
					sb.append(strDeli);
			}

		} catch (Exception e) {
			return null;
		}
		return sb.toString();
	}

	public static Date getMonth(Date currentDate, int c) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(currentDate);
		cal.add(GregorianCalendar.MONTH, c);//在月份上加1
		return cal.getTime();
	}

	public static List<Integer> stringToInteger(String[] s) {
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < s.length; i++) {
			try {

				list.add(Integer.valueOf(s[i]));
			} catch (Exception e) {
				break;
			}
		}
		return list;
	}

	public static void main(String[] args) {
		System.out.println(Tools.getTheSundayDate());
		//		String s="\\boss\\action.do";
		//		System.out.println(s.substring(s.lastIndexOf("\\")+1,s.indexOf(".do")));

		String ss = "2009-10-11";
		System.out.println("fff.jpg".substring("fff.jpg".indexOf("."),"fff.jpg".length()));
		
		System.out.println(ss.substring(0, 4));
		System.out.println(ss.substring(5, 7));
		System.out.println(ss.substring(8, 10));

	}

}